package cn.est.service.impl;

import cn.est.constants.Constants;
import cn.est.exceptions.RedisException;
import cn.est.exceptions.TokenProtectedException;
import cn.est.pojo.Users;
import cn.est.service.TokenService;
import cn.est.utils.RedisUtil;
import cn.est.vo.TokenVo;
import cn.est.vo.WxTokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @ClassName TokenServiceImpl
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2021/4/6 11:30
 * @Version 1.0
 **/
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
   RedisUtil redisUtil ;


    @Override
    public TokenVo genenrateToken(Users users) {
        // String tokenKey="token:"+System.currentTimeMillis()+"_"+MD5Utils.MD5(users.getAccount()).substring(26)+"_"+users.getAccount();
        Long gentime= System.currentTimeMillis();
        String  account= users.getAccount()!=null?users.getAccount():users.getOpenId();
        String tokenKey="token:pc-"+gentime+"-"+ UUID.randomUUID().toString().replace("-","").substring(26)+"-"+ account;
        TokenVo tokenVo=new TokenVo();
        tokenVo.setCreateTime(gentime);
        tokenVo.setToken(tokenKey);
        tokenVo.setOvertime(gentime+Constants.Token.VALID_TIME);
        return  tokenVo;
    }

    @Override
    public TokenVo refreshToken(String oldtoken) throws RedisException, TokenProtectedException {
        //1.有效性校验,校验redis中有没有token
        if(!redisUtil.hasKey(oldtoken)){
            throw new RedisException("redis不存在此token,过期了,请重新登录");
        }
        //2.oldtoken是否没有达到校验的时间，替换时间是oldtoken过期时间的前5分钟
        String oldTokenTime= oldtoken.split("-")[1];
        if(System.currentTimeMillis()-Long.parseLong(oldTokenTime)<Constants.Token.VALID_TIME-Constants.Token.NO_PROTEST_TIME){
            throw new TokenProtectedException("token还在保护期间，不允许置换token");
        }

        //3.生成新的token
        Users user= (Users) redisUtil.get(oldtoken);
       TokenVo tokenVo =genenrateToken(user);
        //4.获取微信的accesstoken
        Object o= redisUtil.get("wx:"+tokenVo.getToken());
        if(o!=null) {
            WxTokenVo wxTokenVo = (WxTokenVo)o;
            wxTokenVo.setTokenVo(tokenVo);
            redisUtil.set("wx:" + tokenVo.getToken(), wxTokenVo, Constants.Token.WX_VALID_TIME);
        }
        //4.新旧token替换
            saveToken(tokenVo.getToken(),user);

        //5.旧的token续钟命2分
            redisUtil.set(oldtoken,user,Constants.Token.DELAY_TIME);
            return  tokenVo;
    }

    @Override
    public void saveToken(String token, Users users) {
        redisUtil.set(token,users, Constants.Duration.HALF_AN_HOUR);
    }

    @Override
    public Users getLoginUser(String token) {
        return (Users) redisUtil.get(token);
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis()-Long.parseLong("1617757058298")<30*60*1000-29.5*60*1000);
    }
}
